<template>
  <!-- 分享链接 -->
  <div class="online_enjoy" v-loading="iframeLoading">
    <!-- 已过期 -->
    <div class="password_box" v-if="isOverdue">
      <div class="title" style="color: red">当前分享链接已过期</div>
    </div>

    <!-- 文件提取密码框 -->
    <div class="password_box" v-if="isPassword">
      <div>
        <div class="title">请输入文件提取密码:</div>
        <div class="box_input">
          <el-input v-model="password"></el-input>
          <el-button type="primary" @click="apiFilesShareShareGetInfo(1)">确定</el-button>
        </div>
      </div>
    </div>

    <!-- 文件展示 -->
    <div v-else class="content_boxs">
      <div class="file_name">
        <svg-icon icon-class="lianjiewenjian"
          style="font-size: 30px; vertical-align: middle; margin-right: 6px"></svg-icon>
        <span>{{ ShareGetInfo.name }}</span>
      </div>

      <div class="title">
        <span>分享人 : {{ ShareGetInfo.personNickname }}</span>

        <span class="title_1">|</span>
        <span>过期时间 : {{ ShareGetInfo.deadline }}</span>
        <!-- <span class="title_1">|</span> -->
      </div>
      <div class="bodys">
        <div class="el_breadcrumb_left">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item class="breadcrumb_item" v-for="(items, indexs) in stratBreadList" :key="indexs"
              @click.native="apiFilesShareShareGetInfo(0)">
              <a>{{ items.label }}</a>
            </el-breadcrumb-item>
            <el-breadcrumb-item v-if="breadList.length != 0"></el-breadcrumb-item>
          </el-breadcrumb>
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item class="breadcrumb_item" v-for="(item, index) in breadList" :key="index"
              @click.native="breadRouterClick(item)">
              <a>{{ item.label }}</a>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div style="padding-top: 12px">
          <el-button @click="downLoadCilck" v-if="ShareGetInfo.isDownload" type="primary">下载</el-button>
        </div>
        <div>
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
            :highlight-current-row="true" @selection-change="handleSelectionChange" @row-dblclick="handleRowDblClick"
            @row-click="handleRowClick">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="文件名" show-overflow-tooltip>
              <template #default="scope">
                <svg-icon :icon-class="selectSvgIcons(scope.row)"
                  style="font-size: 30px; vertical-align: middle; margin-right: 6px"> </svg-icon>
                <span class="realName_class">{{ scope.row.realName }}{{ scope.row.suffix ? '.' + scope.row.suffix : ''
                  }}</span>
              </template>
            </el-table-column>

            <el-table-column label="修改时间">
              <template #default="scope">
                {{ scope.row.updateTime ? scope.row.updateTime : scope.row.createTime }}
              </template>
            </el-table-column>

            <el-table-column label="大小" width="100">
              <template #default="scope">
                <!-- {{ scope.row.size | filterSizeUnit }} -->

                {{ formatSize(scope.row.size) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ApiPerFilesShare, ApiPerShareGetInfo, ApiPershareDirList } from '@/api/personDoc/personDocApi'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

import router from '@/router'
const route = useRoute() // 获取路由信息
const { proxy } = getCurrentInstance() as any
import AvatarImage from '@/assets/images/avatar.png'

const iframeLoading = ref(false)
const Avatar = ref(AvatarImage)
const hash = ref('') as any
const password: any = ref('')
const isPassword = ref(false)
const ShareGetInfo = ref({
  name: '',
  personNickname: '',
  deadline: '',
  isDownload: null,
  downloadsNumber: null,
  id: null,
  isPreview: null,
  visitsNumber: null,
  shareType: '',
})
const rightInfoArray = ref([])
const currentId = ref('')
const FilesTreeDto = ref({})
const breadList = ref([])
const stratBreadList = ref([{ label: '所有文件' }])
const tableData = ref([])
const tableRowArray = ref([])
const isShow = ref(true)
const DownloadNumberList = ref({})
const isOverdue = ref(false)

const formatSize = (size: number) => {
  return proxy.$yuUtils.filterSizeUnit(size)
}
//*表格------------start*/
// 当选择项发生变化时会触发该事件
const handleSelectionChange = (selection) => {
  tableRowArray.value = selection
}

// 双击表格的行
const handleRowDblClick = (val) => {
  // 隐藏下载按钮
  isShow.value = false
  // 展开左边树
  if (val.type == 'folder') {
    apiFilesShareShareDirList(val)
    currentId.value = val.id
  }

  if (val.type == 'file') {
    let routerObj = {
      fileId: val.id,
      id: ShareGetInfo.value.id,
      edition: val.edition
    }
    let path

    if (ShareGetInfo.value.isPreview == 1) {
      // 跳转 -重定向跳转(文件预览)
      val.shareId = ShareGetInfo.value.id
      val.libraryType = 'share'
      if (ShareGetInfo.value.shareType == 'team') {
        val.shareType = 'team'
      } else {
        val.shareType = 'personal'
      }

      proxy.$yuUtils.previewSkipPage(val)




      return
      if (proxy.$yuUtils.suffixLists.includes(val.suffix)) {
        console.log(val.suffix)

        // if (this.$store.state.app.onlinePreview.toLocaleLowerCase() == 'iceblue') {
        //   path = '/enjoyPreview-iceBlue';
        // } else if (this.$store.state.app.onlinePreview.toLocaleLowerCase() == 'onlyoffice') {
        //   path = '/enjoyPreview-onlyOffice';
        // } else {
        //   path = '/enjoyPreview-kk';
        // }
      }

      // else {
      //   path = '/enjoyPreview-kk';
      // }
      const { href } = router.resolve({
        path: path,
        query: routerObj
      })
      window.open(href, '_blank')
    } else {
      ElMessage.warning('无权预览')
    }
  }
}

// 单击表格的行选中
const handleRowClick = (val) => {
  rightInfoArray.value = []
  // this.rightInfoArray.push(val);
}
//*表格------------end*/
// 查询信息
const apiFilesShareShareGetInfo = (visits = 0) => {
  isShow.value = true
  iframeLoading.value = true
  let oParam = {
    hash: hash.value,
    password: password.value,
    userId: userStore.userId
  }
  ApiPerShareGetInfo(oParam).then((res) => {
    iframeLoading.value = false
    if (res.code == 414) {
      ElMessage.error(res.msg)
      return
    }
    if (res.code == 415) {
      ElMessage.error(res.msg)
      return
    }
    if (res.code == 416) {
      ElMessage.error(res.msg)
      return
    }
    if (res.code == 417) {
      ElMessage.error(res.msg)
      return
    }
    breadList.value = []
    tableData.value = []
    // 赋值res
    ShareGetInfo.value = res.data

    router.push({
      path: route.path,
      query: {
        hash: route.query.hash,
        password: password.value
      }
    })

    // 密码输入框关闭
    isPassword.value = false
    // 拿到对应的文件列表
    // tableData.value = res.data.personalFilesTreeVos;
    if (res.data.shareType == 'team') {
      tableData.value = res.data.teamFilesTreeDtos
    } else {
      tableData.value = res.data.personalFilesTreeVos
    }

    if (visits == 1) {
      //为1的时候调用修改访问次数限制
      if (ShareGetInfo.value.downloadsNumber != undefined && ShareGetInfo.value.isPreview == 1) {
        ShareGetInfo.value.visitsNumber = ShareGetInfo.value.visitsNumber - 1

        // enjoyApi.apiFilesShare({
        //   id: this.ShareGetInfo.id,
        //   visitsNumber: this.ShareGetInfo.visitsNumber
        // });
      }
    }
  })
}

//点击面包屑
const breadRouterClick = (val) => {
  for (let i = 0; i < breadList.value.length; i++) {
    if (val.id == breadList.value[i].id) {
      let indexs = i
      breadList.value = breadList.value.slice(0, indexs + 1)
    }
  }

  apiFilesShareShareDirList(val)
}

// 下载
const downLoadCilck = () => {
  if (ShareGetInfo.value.isDownload == 0) {
    ElMessage.warning('无权限下载,请联系分享人')
    return
  }
  if (ShareGetInfo.value.downloadsNumber == 0 && ShareGetInfo.value.isDownload == 1) {
    ElMessage.warning('下载次数已用完')
    return
  }

  if (ShareGetInfo.value.shareType == 'team') {
    let ids = tableRowArray.value.map((item: any) => item.id)
    let info = {
      id: ShareGetInfo.value.id,
    }
    proxy?.$download.downloadFile(ids, 'share', info)

  } else {
    if (tableRowArray.value.length != 0) {
      let ids = tableRowArray.value.map((item: any) => item.id)
      proxy?.$download.downloadFile(ids, tableRowArray.value[0].libraryType)

      // if (ShareGetInfo.value.downloadsNumber && ShareGetInfo.value.downloadsNumber != 0) {
      //   ShareGetInfo.value.downloadsNumber = ShareGetInfo.value.downloadsNumber - 1;
      //   enjoyApi
      //     .apiFilesShare({
      //       id: ShareGetInfo.value.id,
      //       downloadsNumber: ShareGetInfo.value.downloadsNumber
      //     })
      //     .then((res) => {
      //       ShareGetInfo.value.downloadsNumber = res.downloadsNumber;
      //     });
      // }
    } else {
      ElMessage.warning('请选择文件')
    }
  }
}

//获取子级目录
const apiFilesShareShareDirList = (item) => {
  iframeLoading.value = true
  tableData.value = []
  let oParam = {
    hash: hash.value,
    password: password.value,
    pid: item.id
  }
  ApiPershareDirList(oParam).then((res) => {
    iframeLoading.value = false
    if (res.data.shareType == 'team') {
      tableData.value = res.data.teamFilesTreeDtos
    } else {
      tableData.value = res.data.personalFilesTreeVos
    }
    getTreeNode(item)
  })
}

/*面包屑导航栏start--------------*/
const getTreeNode = (node) => {
  // console.log(node, "node");
  if (node && node.realName) {
    let obj = {
      id: node.id,
      label: node.realName
    }
    breadList.value.push(obj)
  }
}

// icon替换
const selectSvgIcons = (v) => {
  return proxy.$yuUtils.selectSvgIcon(v)
}

// 获取文件情况
const routeHash = () => {
  // console.log(route.query.hash, '地址栏');
  // 如果 query.hash 存在并且是字符串类型
  if (typeof route.query.hash === 'string') {
    // 处理包含 '?' 的 hash
    if (route.query.hash.includes('?')) {
      hash.value = route.query.hash.split('?')[0] // 获取 '?' 前的部分

      // 如果 hash 中包含 '='，提取出密码
      if (route.query.hash.includes('=')) {
        password.value = route.query.hash.split('=')[1]
      }
    } else {
      hash.value = route.query.hash // 如果没有 '?'，直接赋值
    }
  }

  apiFilesShareValid()

  // // yu-企业微信链接点开
  // if (route.query.code) {
  //   WxLogin(route.query);
  // }
  // const savedPassword = route.query.password;
  // if (savedPassword) {
  //   password.value = savedPassword;
  //   apiFilesShareShareGetInfo(1);
  // }
}

// hash验证
const apiFilesShareValid = () => {
  let oParam = {
    hash: hash.value
  }

  ApiPerFilesShare(oParam).then((res) => {
    if (res.data == 412) {
      if (password.value) {
        apiFilesShareShareGetInfo(1)
      } else {
        isPassword.value = true
      }
    } else if (res.code == 417) {
      isOverdue.value = true
      // this.$message.error(res.message);
    } else if (res.code == 413) {
      //需要登录
      ElMessage.error(res.msg)

      router.push(`/login?redirect=${route.fullPath}`)
    } else if (res.code == 411) {
      //失效
      ElMessage.error(res.msg)
    } else {
      apiFilesShareShareGetInfo(1)
    }
  })
}

// 企业微信授权登录
const WxLogin = (row) => {
  let userInfo = {
    code: row.code,
    state: row.state,
    appid: ''
  }
  proxy?.$store.dispatch('WWLogin', userInfo)
}

onMounted(() => {
  routeHash()
})
</script>

<style lang="scss" scoped>
.online_enjoy {
  height: 100vh;
  width: 100%;
  overflow: auto;
  background-color: #fafafa;
}

.Online_title {
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #e6e6e6;

  .userClass {
    display: flex;
    align-items: center;
  }

  .avatar-wrapper {
    // margin-top: 5px;
    // position: relative;

    .user-avatar {
      cursor: pointer;
      width: 40px;
      height: 40px;
      border-radius: 10px;
    }
  }
}

.password_box {
  width: 1024px;
  height: 50vh;
  background-color: #fff;
  margin: 0 auto;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;

  .title {
    font-size: 20px;
    margin-bottom: 15px;
  }

  .box_input {
    width: 400px;
    display: flex;

    button {
      margin-left: 20px;
    }
  }
}

.el-breadcrumb__inner:hover {
  color: #409eff !important;
}

.el_breadcrumb_left {
  height: 30px;
  line-height: 30px;
  display: flex;
  // justify-content: space-between;
  align-items: center;
  color: #409eff !important;
}

.content_boxs {
  width: 1024px;
  height: calc(100vh - 100px);
  overflow: auto;
  background-color: #fff;
  margin: 20px auto 0;
  border: 1px solid #e6e6e6;
  padding: 12px;

  .file_name {
    color: #666a6c;
    margin-bottom: 12px;
  }

  .title {
    width: 100%;
    border-bottom: 1px solid #e6e6e6;
    padding-bottom: 12px;
    color: #a1a7aa;
    font-size: 14px;
    text-align: left;
  }

  .title_1 {
    margin: 0 6px;
  }

  .bodys {
    padding-top: 12px;
  }
}

@media screen and (max-width: 750px) {
  .password_box {
    width: 100%;

    .title {
      font-size: 16px;
      text-align: center;
    }

    .box_input {
      width: 50%;
      display: block;
      margin: 0 auto;

      .password_input {
        width: 200px;
      }

      .password_btn {
        margin-top: 10px;
        width: 200px;
        margin-left: 0;
      }
    }
  }

  .content_boxs {
    width: 100%;
    height: calc(100vh - 100px);
    overflow: auto;
    background-color: #fff;
    margin: 20px auto 0;
    border: 1px solid #e6e6e6;
    padding: 12px;

    .file_name {
      color: #666a6c;
      margin-bottom: 12px;
    }

    .title {
      width: 100%;
      border-bottom: 1px solid #e6e6e6;
      padding-bottom: 12px;
      color: #a1a7aa;
      font-size: 14px;
      text-align: left;
    }

    .title_1 {
      margin: 0 6px;
    }

    .bodys {
      padding-top: 12px;
    }
  }
}
</style>
